跳到主要内容

Cherry-pick 精准移植提交

Cherry-pick:精准移植提交

Cherry-pick 是 Git 中一个强大的命令,它允许你从一个分支"挑选"特定的提交,并将其应用到当前分支上。这在需要将热修复、特定功能或实验性代码移植到不同分支时特别有用。

基本 Cherry-pick 操作

单个提交的挑选

# 切换到目标分支
git checkout target-branch

# 挑选特定提交
git cherry-pick <commit-hash>

# 示例:挑选修复bug的提交
git cherry-pick a1b2c3d

在实际开发场景中,假设你正在开发一个电商系统:

// 在功能分支上修复了一个关键的价格计算bug
func CalculatePrice(item Item, discount float64) float64 {
basePrice := item.Price
// 修复:折扣应该是乘法而不是加法
finalPrice := basePrice * (1 - discount) // 之前错误地写成了 basePrice + discount
return finalPrice
}

这个修复需要立即应用到生产环境,但功能分支还有其他未完成的代码。此时 cherry-pick 就发挥了作用:

# 从功能分支挑选修复提交到主分支
git checkout main
git cherry-pick fix-price-calculation-bug

批量挑选提交

# 挑选连续的多个提交
git cherry-pick start-commit^..end-commit

# 挑选不连续的多个提交
git cherry-pick commit1 commit2 commit3

# 示例:挑选一系列相关的性能优化提交
git cherry-pick perf-opt-1 perf-opt-2 perf-opt-3

Cherry-pick 冲突解决

当挑选的提交与当前分支有冲突时,Git 会暂停操作等待你解决:

# 发生冲突时的状态
$ git cherry-pick a1b2c3d
error: could not apply a1b2c3d... Fix user authentication
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

# 查看冲突文件
git status

# 手动解决冲突后
git add .
git cherry-pick --continue

# 如果要放弃当前挑选
git cherry-pick --abort

Cherry-pick 高级选项

# 挑选时不自动提交,仅添加到暂存区
git cherry-pick -n <commit-hash>

# 挑选时编辑提交信息
git cherry-pick -e <commit-hash>

# 挑选时添加签名信息
git cherry-pick -s <commit-hash>

# 保留原始作者和提交时间
git cherry-pick -x <commit-hash>

Cherry-pick 最佳实践

  1. 提交独立性:确保挑选的提交是自包含的,不依赖其他提交
  2. 测试验证:挑选后务必在目标分支上测试功能
  3. 文档记录:在提交信息中记录挑选的来源